import { constantRoutes } from "@/router";
import { getMenu } from "@/api/menu";
import Layout from "@/layout/index";

const getDefaultState = () => {
    return {
			menus: [],
			routes: [],
			addRoutes: []
    }
}

const state = getDefaultState();

const menu = {
    namespaced: true,
		state: state,
		mutations: {
			SET_ROUTES: (state, routes) => {
				state.addRoutes = routes
				state.routes = constantRoutes.concat(routes)
			},
			SET_MENUS: (state, menus) => {
				state.menus = menus
			},
		},
		actions: {
			// 初始化菜单
			InitMenu({commit}) {
				return new Promise(resolve => {
					// 向后端发送请求，获取菜单数据
					getMenu().then(resp => {
						const menuData = resp.data
						const menus = formatMenu(menuData)
						const rewriteMenus = formatMenu(menuData)

						rewriteMenus.push({ path: '*', redirect: '/404', hidden: true })

						commit('SET_ROUTES', rewriteMenus)
						commit('SET_MENUS', menus)

						resolve(rewriteMenus)
					})
				})
			}
		}
}

// 格式化菜单数据，生成组件对象
function formatMenu(routers) {

	let fmtRouters = []

	routers.forEach((route) => {
		let {
			navId,
			item,
			icon,
			path,
			component,
			children
		} = route
		
		if (children && children instanceof Array && children.length > 0) {
			// 递归
			children = formatMenu(children)
		}

		let fmRoute = {
			path: path,
			name: item,
			meta: {title: item, icon: icon, navId: navId}
		}

		if (component === 'Layout') {
			fmRoute.component = Layout
		} else {
			fmRoute.component = loadMenu(component)
		}

		if (children && children.length > 0) {
			fmRoute.children = children
			fmRoute.redirect = path + '/' + children[0].path
		}

		fmtRouters.push(fmRoute)
	})

	return fmtRouters
}

const loadMenu = (menu) => {
	if (process.env.NODE_ENV === 'development') {
		return (resolve) => require([`@/views/${menu}`], resolve)
	} else {
		return () => import(`@/views/${menu}`)
	}
}

export default menu